<!-- 调拨管理 -->
<template>
  <div class="app-main-container">
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getList(1)" @clear="clear" />
    <div v-if="meta.indexOf('AllotManagerAdd') > -1" class="doumee_table_header">
      <el-button type="primary" @click="putStorageAdd">{{ $t('message.add') }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column align="center" :label="$t('message.dbdh2')" prop="orderId" min-width="210" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.spxx')" min-width="250" prop="type" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.goodsList && scope.row.goodsList.length > 0 ? scope.row.goodsList[0].name + 'x' +
            scope.row.goodsList[0].count : '' }}
          <span style="word-spaceing: 10px" />
          <span style="word-spaceing: 10px" />
          <el-button
            v-if="scope.row.goodsList.length > 1 && meta.indexOf('AllotManagerGoodsList') > -1"
            size="small"
            icon="el-icon-more"
            @click="toShowGoodsList(scope.row.goodsList)"
          >
            <i class="el-icon-more" />
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.shcg')" prop="toVenueName" min-width="200" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.status')" min-width="100" show-overflow-tooltip>
        {{ $t('message.ydb') }}
      </el-table-column>
      <el-table-column align="center" :label="$t('message.czy')" prop="creator" min-width="120" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.dbsj')" min-width="160" prop="createDate" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.bz')" prop="info" min-width="300" max-height="200" show-overflow-tooltip />
    </el-table>
    <Paginations :total="totalCount" :page="pagination.page" @current-change="getList" @SizeChange="handleSizeChange" />
    <el-dialog
      :title="$t('message.add')"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showPutStorageAdd"
      width="750px"
      :before-close="willClose"
    >
      <div class="add-item">
        <div class="add-item-header">
          <div class="title"><span style="color: red;">* </span>{{ $t('message.dbsp') }}：</div>
          <div class="content">

            <el-input
              ref="barcode"
              v-model="addPutSInfo.barCode"
              class="barcode"
              :placeholder="$t('message.txmdjsmhq')"
              @input="barcodeChange"
            />
            <el-select v-model="addPutSInfo.id" class="goods" :placeholder="$t('message.xzsp3')" @change="putInfoValueChange">
              <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input
              v-model="addPutSInfo.count"
              class="num"
              :placeholder="$t('message.dbsl')"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              oninput="if(value<=0) { value = ''}"
            />
            <el-button type="primary" class="btnitem" @click="putAdd()">{{ $t('message.add') }}</el-button>
          </div>

        </div>
        <div v-for="(item, index) in addGoodsList" :key="item.id" class="add-item-goods">
          <span class="title"> {{ item.name }}</span>
          <div class="content">
            <el-input v-model="item.barCode" class="barcode" disabled :placeholder="$t('message.rksl')" />
            <el-select v-model="item.id" class="goods" :placeholder="$t('message.xzsp3')" @change="addItemValueChange">
              <el-option v-for="goods in goodsList" :key="goods.id" :label="goods.name" :value="goods.id" />
            </el-select>
            <el-input
              v-model="item.count"
              class="num"
              :placeholder="$t('message.dbsl')"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              oninput="if(value<=0) { value = ''}"
            />
            <el-button class="btnitem secondColor" @click="deleteItem(index)">{{ $t('message.del') }}</el-button>
          </div>

        </div>
        <div class="add-item-vunue">
          <div class="title"><span style="color: red;">* </span>{{ $t('message.shcg') }}：</div>
          <div class="content">
            <el-select v-model="venueId" :placeholder="$t('message.shcg')" clearable class="venue">
              <el-option v-for="item in venueList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </div>
        </div>
        <div class="add-item-footer">
          <span class="title"> {{ $t('message.bz') }}：</span>
          <div class="content">
            <el-input v-model="remark" class="remark" :placeholder="$t('message.qsr') + $t('message.bz')" />
          </div>

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPutStorage">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="confirmPutStorage">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.splb')"
      :visible.sync="showMoreGoods"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :before-close="moreGoodsWillClose"
    >
      <el-table :data="showGoodsList" border fit class="doumee-element-table">
        <el-table-column align="center" :label="$t('message.spmc')" prop="name" />

        <el-table-column align="center" :label="$t('message.spjg')" prop="price" />
        <el-table-column align="center" :label="$t('message.dbsl')" prop="count" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  inventoryList,
  inventoryAdd,
  queryByBarCode,
  goodsListVenue,
  inventoryVenueList
} from '@/api'
import QueryForm from '@/components/QueryForm'
import store from '@/store'
import { parseTime } from '@/utils'
export default {
  name: 'AllotManager',
  components: {
    QueryForm
  },
  data() {
    return {
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: this.$t('message.dbdh2'),
          clearable: true
        }, {
          filed: 'time',
          type: 'daterange',
          clearable: true
        }, {
          filed: 'toVenueId',
          type: 'select',
          label: this.$t('message.shcg'),
          clearable: true,
          options: []
        }],
        online: true
      },
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      totalCount: 0,
      listLoading: true,
      list: [],
      goodsList: [],
      venueList: [],
      addGoodsList: [],
      showGoodsList: [],
      showMoreGoods: false,
      showPutStorageAdd: false,
      remark: '',
      venueId: '',
      addPutSInfo: {},
      putStorageList: [],
      filters: {
        time: []
      },
      pagination: {
        page: 1,
        rows: 10
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
    this.getGoodsListByVenue()
    this.getVenueList()
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      filters.venueId = sessionStorage.getItem('venueId')
      filters.type = '1'
      this.listLoading = true
      inventoryList({
        pagination,
        param: {
          ...filters
        },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.totalCount = res.totalCount
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 场馆端商品列表
    getGoodsListByVenue() {
      goodsListVenue({
        param: {
          status: '',
          type: '1',
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.goodsList = res.recordList
        })
        .catch(() => { })
    },
    getVenueList() {
      inventoryVenueList({
        param: {
          venueId: sessionStorage.getItem('venueId')
        },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          const arr = res.recordList
          arr.forEach(e => {
            e.label = e.name
            e.value = e.id
          })
          this.venueList = arr
          this.queryFormConfig.formItems[2].options = arr
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 调拨新增操作
    putAdd() {
      if (!this.addPutSInfo.barCode) {
        this.$message.warning(this.$t('message.shcg') + this.$t('message.sptxm'))
        return
      }
      if (!this.addPutSInfo.id) {
        this.$message.warning(this.$t('message.qxzydbdsp'))
        return
      }
      if (!this.addPutSInfo.count) {
        this.$message.warning(this.$t('message.qsrydbdsl'))
        return
      }
      const temp = this.addGoodsList.find(item => item.id === this.addPutSInfo.id)
      if (temp) {
        this.$message.warning(this.$t('message.dbdspycz'))
        return
      }
      const item = JSON.stringify(this.addPutSInfo)
      const goodsinfo = JSON.parse(item)
      this.addGoodsList.push(goodsinfo)
      this.addPutSInfo = {}
      this.$refs.barcode.focus()
    },
    // 删除调拨商品
    deleteItem(idx) {
      this.addGoodsList.splice(idx, 1)
    },
    // 条形码输入
    barcodeChange(barCode) {
      if (!barCode) {
        return
      }

      queryByBarCode({
        param: {
          barCode: barCode,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          const record = res.record
          if (!record) {
            this.addPutSInfo.barCode = ''
            this.addPutSInfo.id = ''
          } else {
            this.addPutSInfo.id = record.id
            this.addPutSInfo.barCode = record.barCode
          }
        })
        .catch(() => { })
    },
    putInfoValueChange(val) {
      if (!val) {
        return
      }
      if (!this.goodsList) {
        return
      }
      const temp = this.goodsList.find(item => item.id === val)
      if (temp) {
        this.addPutSInfo.barCode = temp.barCode
      }
      // for (const idx in this.goodsList) {
      //   const goods = this.goodsList[idx]
      //   if (goods.id === val) {
      //     this.addPutSInfo.barCode = goods.barCode
      //   }
      // }
    },
    addItemValueChange(val) {
      if (!val) {
        return
      }
      if (!this.goodsList) {
        return
      }
      const goods = this.goodsList.find(item => item.id === val)
      if (!goods) {
        return
      }
      const temp = this.addGoodsList.find(item => goods.id === item.id)
      if (temp) {
        temp.barCode = goods.barCode
      }
      // for (const idx in this.goodsList) {
      //   const goods = this.goodsList[idx]
      //   if (goods.id === val) {
      //     for (const selidx in this.addGoodsList) {
      //       const item = this.addGoodsList[selidx]
      //       if (goods.id === item.id) {
      //         item.barCode = goods.barCode
      //       }
      //     }
      //   }
      // }
    },
    toShowGoodsList(item) {
      this.showGoodsList = item
      this.showMoreGoods = true
    },
    moreGoodsWillClose(done) {
      this.showGoodsList = []
      done()
    },
    handleCurrentChange(page) {
      this.filters.page = page
      this.getList()
    },
    clear() {
      this.filters = { time: [] }
      this.getList(1)
    },
    putStorageAdd() {
      this.showPutStorageAdd = true
      setTimeout(() => {
        this.$refs.barcode.focus()
      }, 300)
    },
    cancelPutStorage() {
      this.showPutStorageAdd = false
      this.clearPutStorageInfo()
    },
    willClose(done) {
      this.clearPutStorageInfo()
      done()
    },
    clearPutStorageInfo() {
      this.venueId = ''
      this.remark = ''
      this.addGoodsList = []
      this.putStorageList = []
      this.addPutSInfo = {
        id: '',
        barCode: '',
        count: ''
      }
    },
    confirmPutStorage() {
      if (!this.addGoodsList.length) {
        this.$message.warning(this.$t('message.qtjdbsp'))
        return
      }
      if (!this.venueId) {
        this.$message.warning(this.$t('message.qxz') + this.$t('message.shcg'))
        return
      }
      const goods = this.addGoodsList.find(item => !item.count)
      if (goods) {
        this.$message.warning(this.$t('message.qsrydbdsl'))
        return
      }
      // for (const goods of this.addGoodsList) {
      //   if (!goods.count) {
      //     this.$message.warning(this.$t('message.qsrydbdsl'))
      //     return
      //   }
      // }
      this.subLoading = true
      inventoryAdd({
        param: {
          goodsList: this.addGoodsList,
          type: '1',
          info: this.remark,
          toVenueId: this.venueId,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.subLoading = false
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.dbcg'))
          this.showPutStorageAdd = false
          this.clearPutStorageInfo()
          this.getList(1)
        })
        .catch(() => {
          this.subLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-item {
  .add-item-header {
    display: flex;

    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }

    .content {
      .barcode {
        margin-left: 10px;
        width: 200px;
      }

      .goods {
        margin-left: 10px;
        width: 150px;
      }

      .num {
        margin-left: 10px;
        margin-right: 20px;
        width: 90px;
      }
    }
  }

  .add-item-goods {
    display: flex;
    margin-top: 10px;

    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }

    .content {
      .barcode {
        margin-left: 10px;
        width: 200px;
      }

      .goods {
        margin-left: 10px;
        width: 150px;
      }

      .num {
        margin-left: 10px;
        margin-right: 20px;
        width: 90px;
      }
    }
  }

  .add-item-vunue {
    display: flex;
    margin-top: 10px;

    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }

    .content {
      width: 81%;

      .venue {
        margin-left: 10px;

      }
    }
  }

  .add-item-footer {
    display: flex;
    margin-top: 10px;

    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }

    .content {
      width: 81%;

      .remark {
        margin-left: 10px;
      }
    }
  }
}
</style>

